import { defineStore } from 'pinia'
import { asyncRoutes, constantRoutes } from '@/router/index'
import { filterAsyncRoutes } from '@/utils/routers'
import { filterKeepAlive } from '@/utils/routers'
import { getAuthors } from '@/api/role'
import routerList from '../../utils/routerList.json'
import { useUserStore } from '@/store/modules/user'

import Layout from '@/layout/index.vue'
import { RouteRecordRaw } from 'vue-router'
import _ from 'lodash'
export const usePermissionStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: 'permissionState',
  // state: 返回对象的函数
  state: () => ({
    // 路由
    routes: [],
    // 动态路由
    addRoutes: [],
    // 缓存路由
    cacheRoutes: {},
    // 权限列表
    roleList: [],
  }),
  getters: {
    /**
     * 该权限控制时控制菜单的显示，这种方式不好，因为只适用于只有两层权限的情况下，如果有多层，就会出现问题，所以未来要改成递归的方式
     */
    permission_routes: (state) => {
      // 返回结果
      const result: Array<RouteRecordRaw & { hidden: boolean }> = []

      // 深度拷贝是为了不影响state.routes
      _.cloneDeep(state.routes).forEach((route) => {
        // 获取一级权限，就是权限数组最外层的那部分
        // 如果name值相等就代表该路由对应的菜单显示出来，否则就不显示
        const firstRole = state.roleList.find((role) => role.name === route.name)

        // 获取一级路由，并控制菜单的显示状态
        const firstRoute = Object.assign(route, {
          hidden: firstRole ? !!firstRole.hidden : true,
        })
        if (!firstRoute.meta) {
          if (firstRole && firstRole.meta) {
            firstRoute.meta = firstRole.meta
          }
        } else {
          /**
           * 使用后端返回的标题
           */
          if (firstRole && firstRole.meta && firstRole.meta.title) {
            firstRoute.meta.title = firstRole.meta.title
          }
        }

        if (firstRole) {
          // 二级路由列表
          const __childrenRoutes: Array<RouteRecordRaw & { hidden: boolean }> = []

          // 遍历二级路由，并控制菜单的显示状态
          firstRoute.children.forEach((childrenRoute) => {
            // 二级权限，就是权限列表的第二层那部分
            // 如果name值相等就代表此路由对应的菜单显示出来，否则就不显示
            const secondRole = firstRole.authorVos.find(
              (authorVo) => authorVo.name === childrenRoute.name,
            )

            if (secondRole) {
              const secondRoute = Object.assign(childrenRoute, {
                hidden: secondRole ? secondRole.hidden : true,
              })
              if (!secondRoute.meta) {
                if (secondRole && secondRole.meta) {
                  secondRoute.meta = secondRole.meta
                }
              } else {
                /**
                 * 使用后端返回的标题
                 */
                if (secondRole && secondRole.meta && secondRole.meta.title) {
                  secondRoute.meta.title = secondRole.meta.title
                }
              }

              // 组装二级路由列表
              __childrenRoutes.push(secondRoute)
            }
          })

          // 更新二级路由
          firstRoute.children = __childrenRoutes
        }

        if (firstRole) {
          // 组装一级路由列表
          result.push(firstRoute)
        }
      })
      return result
    },
    keepAliveRoutes: (state) => {
      return filterKeepAlive(asyncRoutes)
    },
  },
  // 可以同步 也可以异步
  actions: {
    // 生成路由
    generateRoutes(roles) {
      const UserStore = useUserStore()
      return new Promise(async (resolve) => {
        // 在这判断是否有权限，哪些角色拥有哪些权限
        let accessedRoutes
        if (roles && roles.length && !roles.includes('admin')) {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        } else {
          if (UserStore.token) {
            const res = await getAuthors()
            if (res) {
              if (res.data.success) {
                this.roleList = res.data.data.rows || []
              }
              // else {
              //     UserStore.token = null
              //     UserStore.roles = []
              //     UserStore.row = {
              //         tokenValue: null,//登录token
              //         expireIn: null,//过期时间
              //         tokenStartTime: null,//登录当前时间
              //         refreshToken: null,//刷新token
              //         tokenName: null,
              //     }
              //     UserStore.logout()
              // }
            } else {
              this.roleList = []
            }

            const modules = import.meta.glob('@/views/**/index.vue')
            const routerListarr = routerList[0].filter((o) => {
              return o.path
            })
            const accessedRoutes2 = routerListarr.map((o) => {
              const temp = {
                name: o.name,
                path: o.path,
                component: Layout,
                meta: {
                  title: o.meta.title,
                  icon: o.meta.icon,
                },
                children: [],
              }
              if (o.authorVos.length > 0) {
                temp.children = o.authorVos.map((i) => {
                  return {
                    name: i.name,
                    path: i.path,
                    component: modules[i.component],
                    meta: {
                      title: i.meta.title,
                      icon: i.meta.icon,
                      keepAlive: true,
                    },
                    hidden: i.hidden,
                  }
                })
              }
              //  else {
              //     temp.children = [{
              //         name: o.name,
              //         path: o.path,
              //         component: modules[o.component],
              //         meta: {
              //             title: o.meta.title,
              //             icon: o.meta.icon,
              //             keepAlive: true
              //         },
              //         children: []
              //     }]
              // }
              return temp
            })

            // accessedRoutes = [...accessedRoutes2, {
            //     path: '/:pathMatch(.*)',
            //     redirect: '/404',
            // }] || []
            accessedRoutes = asyncRoutes || []
          } else {
            accessedRoutes = []
          }
        }

        this.routes = constantRoutes.concat(accessedRoutes)
        this.addRoutes = accessedRoutes
        resolve(accessedRoutes)
      })
    },
    // 清楚路由
    clearRoutes() {
      this.routes = []
      this.addRoutes = []
      this.cacheRoutes = []
      this.roleList = []
    },
    getCacheRoutes() {
      this.cacheRoutes = filterKeepAlive(asyncRoutes)
      return this.cacheRoutes
    },
  },
})
